package com.dense.kuiniu.shelfcard.business.handler;

import com.dense.kuiniu.shelfcard.base.BaseFragment;
import com.dense.kuiniu.shelfcard.base.Url;
import com.dense.kuiniu.shelfcard.business.CardInfoDelegate;
import com.dense.kuiniu.shelfcard.business.CardInfoNextDelegate;
import com.dense.kuiniu.shelfcard.card.idcard.IDCardInfo;
import com.dense.kuiniu.shelfcard.entity.BindInfo;
import com.dense.kuiniu.shelfcard.view.dialog.PutCardDialog;
import com.rxjava.rxlife.RxLife;

import me.yokeyword.fragmentation.ISupportFragment;
import rxhttp.RxHttp;
import rxhttp.wrapper.exception.ParseException;

/**
 * @author Administrator
 * @date 2020/9/24
 */
public class AddCardHandler implements CardHandler {
    @Override
    public void handle(PutCardDialog dialog, BaseFragment fragment, IDCardInfo info) {
        queryCardInfo(dialog, fragment, info);
    }

    private void queryCardInfo(PutCardDialog dialog, final BaseFragment fragment, IDCardInfo info) {
        RxHttp.get(Url.getIdCardInfo)
                .add("idCard", info.getCardNo())
                .asResponse(BindInfo.class)
                .to(RxLife.toMain(fragment))  //感知生命周期，并在主线程回调
                .subscribe(binding -> {
                    ISupportFragment delegate = null;
                    if (binding != null) {
                        delegate = fragment.findFragment(CardInfoDelegate.class);
                        if (delegate == null) {
                            delegate = CardInfoDelegate.getInstance(binding);
                        }
                    }
                    if (dialog != null) {
                        dialog.exit();
                    }
                    fragment.start(delegate);

                }, throwable -> {
                    if (throwable instanceof ParseException) {
                        if ("200".equals(((ParseException) throwable).getErrorCode())) {
                            CardInfoNextDelegate delegate = fragment.findFragment(CardInfoNextDelegate.class);
                            if (delegate == null) {
                                delegate = CardInfoNextDelegate.getInstance(info);
                            }
                            fragment.start(delegate);
                            if (dialog != null) {
                                dialog.exit();
                            }
                        } else {
                            if (dialog != null) {
                                dialog.error(throwable.getMessage());
                            }
                        }
                    } else {
                        if (dialog != null) {
                            dialog.error(throwable.getMessage());
                        }
                    }

                });
    }
}